#include "classroomcomputersettings.h"
#include "./ui_classroomcomputersettings.h"
ClassroomComputerSettings::ClassroomComputerSettings(QWidget *parent) : QMainWindow(parent), ui(new Ui::ClassroomComputerSettings)
{
	ui->setupUi(this);
	setWindowFlags(Qt::WindowStaysOnTopHint);
	loadConfig();
}
ClassroomComputerSettings::~ClassroomComputerSettings() { delete ui; }
int timeStringToMinutes(const QString &timeStr)
{
	QTime time = QTime::fromString(timeStr.trimmed(), "HH:mm");
	if (time.isValid()) return time.hour() * 60 + time.minute();
	return -1;
}
QString minutesToTimeString(int minutes)
{
	if (minutes < 0 || minutes >= 1440) return "--:--";
	return QTime(minutes / 60, minutes % 60).toString("HH:mm");
}
void ClassroomComputerSettings::loadConfig()
{
	Config &config = Config::instance();
	ui->barrage->setChecked(config.barrage());
	ui->screensaver->setChecked(config.screensaver());
	ui->hiddenSubjectsEdit->setText(config.hiddenSubjects());
	QStringList ganfanMinutes = config.ganfanTimes();
	QStringList ganfanTimes;
	for (const QString &minStr : ganfanMinutes) {
		bool ok;
		int minutes = minStr.trimmed().toInt(&ok);
		if (ok) ganfanTimes << minutesToTimeString(minutes);
		else showErrorMessage("干饭时间格式错误: " + minStr);
	}
	ui->mealTimeLineEdit->setText(ganfanTimes.join(", "));
	QStringList shutdownMinutes = config.shutdownTimes();
	QStringList shutdownSchedule;
	for (const QString &minStr : shutdownMinutes) {
		bool ok;
		int minutes = minStr.trimmed().toInt(&ok);
		if (ok) shutdownSchedule << minutesToTimeString(minutes);
		else showErrorMessage("关机时间格式错误: " + minStr);
	}
	ui->shutdownTimeLineEdit->setText(shutdownSchedule.join(", "));
	ui->enrollmentDateTimeEdit->setDateTime(QDateTime::fromSecsSinceEpoch(config.enrollmentTimestamp()));
	ui->GaoKaoDateTimeEdit->setDateTime(QDateTime::fromSecsSinceEpoch(config.gaokaoTimestamp()));
	QFile studentsfile(studentsFilePath);
	if (studentsfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
		ui->studentListPlainTextEdit->setPlainText(QTextStream(&studentsfile).readAll());
		studentsfile.close();
	}
	QFile noticefile(noticeFilePath);
	if (noticefile.open(QIODevice::ReadOnly | QIODevice::Text)) {
		ui->noticePlainTextEdit->setPlainText(QTextStream(&noticefile).readAll());
		noticefile.close();
	}
	ui->longTermScheduleTable->setDisabled(1);
	ui->tempScheduleTable->setDisabled(0);
	ui->removeClassBtn->setDisabled(1);
	ui->subjectListWidget_2->setDisabled(1);
	QFile file(timetableFilePath);
	if (!file.open(QIODevice::ReadOnly)) return;
	ui->longTermTimetableTable->setRowCount(0);
	QTextStream in(&file);
	if (in.readLine() != "开始时间,结束时间,课程标题,周一,周二,周三,周四,周五,周六,周日") showErrorMessage("课程表标题行异常!");
	while (!in.atEnd()) {
		QString line = in.readLine();
		QStringList fields = line.split(",");
		int row = ui->longTermTimetableTable->rowCount();
		ui->longTermTimetableTable->insertRow(row);
		for (int col = 0; col < fields.size(); col++) {
			QTableWidgetItem *item = new QTableWidgetItem(fields.at(col));
			ui->longTermTimetableTable->setItem(row, col, item);
		}
	}
	file.close();
	loadTempTimetable();
}
void ClassroomComputerSettings::showErrorMessage(const QString &message)
{
	ui->statusLabel->setStyleSheet("background-color: #ff0000; color: #ffffff;");
	ui->statusLabel->setText(message);
	isSettingError = 1;
}
void ClassroomComputerSettings::on_longTermTimetableTable_cellClicked(int row, int column)
{
	currentRow = ui->longTermTimetableTable->currentRow();
	ui->removeClassBtn->setDisabled(0);
	if (column >= 3 && column <= 10) {
		ui->subjectListWidget_2->setDisabled(0);
		QString cellText = ui->longTermTimetableTable->item(row, column)->text();
		bool found = false;
		if (cellText == "") {
			ui->subjectListWidget_2->setCurrentItem(ui->subjectListWidget_2->item(0));
			ui->subjectListWidget_2->scrollToItem(ui->subjectListWidget_2->item(0));
			found = true;
		} else {
			for (int i = 1; i < ui->subjectListWidget_2->count(); ++i) {
				QListWidgetItem *subjectItem = ui->subjectListWidget_2->item(i);
				if (subjectItem->text() == cellText) {
					ui->subjectListWidget_2->setCurrentItem(subjectItem);
					ui->subjectListWidget_2->scrollToItem(subjectItem);
					found = true;
					break;
				}
			}
		}
		if (!found) ui->subjectListWidget_2->clearSelection();
	} else {
		ui->subjectListWidget_2->clearSelection();
		ui->subjectListWidget_2->setDisabled(1);
	}
}
void ClassroomComputerSettings::on_subjectListWidget_2_itemClicked(QListWidgetItem *item)
{
	if (currentRow == -1) {
		ui->subjectListWidget_2->clearSelection();
		return;
	}
	QTableWidgetItem *selectedCell = ui->longTermTimetableTable->currentItem();
	if (selectedCell) {
		QString text = (item->text() == "(空)") ? "-" : item->text();
		selectedCell->setText(text);
		int currentCol = ui->longTermTimetableTable->currentColumn();
		int totalRows = ui->longTermTimetableTable->rowCount();
		int totalCount = ui->longTermTimetableTable->columnCount();
		if (currentRow == totalRows - 1) {
			if (currentCol >= 3 && currentCol < 10) {
				currentCol++;
				currentRow = 0;
			}
			if (ui->longTermTimetableTable->currentColumn() == totalCount - 1) {
				ui->subjectListWidget_2->setDisabled(1);
				ui->removeClassBtn->setDisabled(1);
				currentRow = 0;
			}
		} else currentRow++;
		ui->longTermTimetableTable->setCurrentCell(currentRow, currentCol);
		ui->longTermTimetableTable->scrollToItem(ui->longTermTimetableTable->item(currentRow, currentCol));
		ui->longTermTimetableTable->setFocus();
	}
	ui->subjectListWidget_2->clearSelection();
}
void ClassroomComputerSettings::loadTempTimetable(int targetDayOfWeek)
{
	ui->subjectListWidget->setDisabled(1);
	if (QFile::exists(tempTimetableFilePath) && QFile::exists(timetableFilePath)) {
		QFile timetableFile(timetableFilePath);
		QFile tempFile(tempTimetableFilePath);
		if (timetableFile.open(QIODevice::ReadOnly) && tempFile.open(QIODevice::ReadOnly)) {
			QTextStream in(&timetableFile), tempIn(&tempFile);
			in.readLine();
			int timetableRowCount = 0, tempRowCount = 0;
			while (!in.atEnd()) {
				in.readLine();
				timetableRowCount++;
			}
			timetableFile.close();
			while (!tempIn.atEnd()) {
				tempIn.readLine();
				tempRowCount++;
			}
			tempFile.close();
			if (tempRowCount != timetableRowCount) on_deleteTempScheduleBtn_clicked();
		}
	}
	QTableWidget *tempTable = ui->TempTimetableTable;
	QFile timetableFile(timetableFilePath);
	if (!timetableFile.open(QIODevice::ReadOnly)) return;
	tempTable->clearContents();
	tempTable->setRowCount(0);
	QTextStream timetableIn(&timetableFile);
	timetableIn.readLine();
	QStringList timeHeaders;
	while (!timetableIn.atEnd()) {
		QStringList fields = timetableIn.readLine().split(",");
		if (fields.size() > 2) { timeHeaders << fields[2].trimmed(); }
	}
	timetableFile.close();
	tempTable->setRowCount(timeHeaders.size());
	tempTable->setColumnCount(1);
	for (int i = 0; i < timeHeaders.size(); ++i) tempTable->setVerticalHeaderItem(i, new QTableWidgetItem(timeHeaders[i]));
	QStringList courses;
	if (QFile::exists(tempTimetableFilePath)) {
		QFile file(tempTimetableFilePath);
		if (file.open(QIODevice::ReadOnly)) {
			QTextStream in(&file);
			while (!in.atEnd()) {
				QString course = in.readLine().trimmed();
				if (!course.isEmpty()) courses << course;
			}
			file.close();
		}
	} else {
		QFile file(timetableFilePath);
		if (file.open(QIODevice::ReadOnly)) {
			QTextStream in(&file);
			in.readLine();
			if (targetDayOfWeek < 1 || targetDayOfWeek > 7) targetDayOfWeek = QDateTime::currentDateTime().date().dayOfWeek();
			int targetColumn = 3 + (targetDayOfWeek - 1);
			while (!in.atEnd()) {
				QStringList fields = in.readLine().split(",");
				if (fields.size() > targetColumn) courses << fields[targetColumn].trimmed();
			}
			file.close();
		}
	}
	for (int row = 0; row < timeHeaders.size() && row < courses.size(); ++row) tempTable->setItem(row, 0, new QTableWidgetItem(courses[row]));
}
void ClassroomComputerSettings::on_addClassBtn_clicked()
{
	ui->longTermTimetableTable->insertRow(++currentRow);
	if (currentRow > 0) {
		QTime lastEnd = QTime::fromString(ui->longTermTimetableTable->item(currentRow - 1, 1)->text(), "HH:mm");
		QTime newStart = lastEnd.addSecs(480);
		QTime newEnd = newStart.addSecs(2520);
		ui->longTermTimetableTable->setItem(currentRow, 0, new QTableWidgetItem(newStart.toString("HH:mm")));
		ui->longTermTimetableTable->setItem(currentRow, 1, new QTableWidgetItem(newEnd.toString("HH:mm")));
	} else {
		ui->longTermTimetableTable->setItem(0, 0, new QTableWidgetItem("07:30"));
		ui->longTermTimetableTable->setItem(0, 1, new QTableWidgetItem("07:50"));
	}
	for (int col = 2; col < ui->longTermTimetableTable->columnCount(); col++) {
		QTableWidgetItem *item = new QTableWidgetItem(col == 2 ? "新课" : "");
		ui->longTermTimetableTable->setItem(currentRow, col, item);
	}
	ui->longTermTimetableTable->selectRow(currentRow);
	ui->removeClassBtn->setDisabled(0);
	ui->subjectListWidget_2->setDisabled(1);
}
void ClassroomComputerSettings::on_removeClassBtn_clicked()
{
	if (currentRow == -1) return;
	QMessageBox::StandardButton reply;
	reply = QMessageBox::question(this, "删除课时", "确认删除第" + QString::number(currentRow + 1) + "行" + ui->longTermTimetableTable->item(currentRow, 2)->text() + "?", QMessageBox::Yes | QMessageBox::No);
	if (reply == QMessageBox::Yes) {
		ui->removeClassBtn->setDisabled(1);
		ui->subjectListWidget_2->setDisabled(1);
		ui->longTermTimetableTable->removeRow(currentRow);
		currentRow = -1;
	}
}
void ClassroomComputerSettings::on_subjectListWidget_itemClicked(QListWidgetItem *item)
{
	QTableWidgetItem *selectedCell = ui->TempTimetableTable->currentItem();
	if (!selectedCell) {
		ui->statusLabel->setText("请先在临时课表中选择要设置的单元格");
		return;
	}
	QString text = (item->text() == "(空)") ? "-" : item->text();
	selectedCell->setText(text);
}
void ClassroomComputerSettings::on_TempTimetableTable_cellClicked(int row, int column) { ui->subjectListWidget->setDisabled(0); }
void ClassroomComputerSettings::on_tabWidget_currentChanged(int index)
{
	if (index == 1 && ui->tempScheduleTable->isEnabled()) {
		if (QMessageBox::question(this, "课程表", "修改长期课程表将删除并禁用临时课表(本次), 是否继续?", QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
			on_deleteTempScheduleBtn_clicked();
			ui->tempScheduleTable->setDisabled(1);
			ui->longTermScheduleTable->setDisabled(0);
		}
	}
}
void ClassroomComputerSettings::on_hiddenSubjectsListWidget_itemClicked(QListWidgetItem *item)
{
	QString selected = item->text();
	QLineEdit *edit = ui->hiddenSubjectsEdit;
	QString current = edit->text();
	if (selected == "⌫删除") {
		if (edit->hasSelectedText()) edit->del();
		else {
			current = current.trimmed();
			while (current.endsWith(',')) current.chop(1);
			int lastComma = current.lastIndexOf(',');
			if (lastComma != -1) edit->setText(current.left(lastComma));
			else edit->clear();
		}
	} else {
		current = current.trimmed();
		if (!current.isEmpty() && !current.endsWith(',')) current += ",";
		current += selected;
		edit->setText(current);
	}
	edit->setCursorPosition(edit->text().length());
}
void ClassroomComputerSettings::on_deleteTempScheduleBtn_clicked()
{
	if (QFile::exists(tempTimetableFilePath)) QFile::remove(tempTimetableFilePath);
	ui->daySelectorComboBox->setCurrentIndex(0);
	ui->statusLabel->setText("临时课表已重置!");
}
void ClassroomComputerSettings::on_daySelectorComboBox_currentIndexChanged(int dayOfWeek) { loadTempTimetable(dayOfWeek); }
void ClassroomComputerSettings::on_restoreDefaultsAction_triggered()
{
	if (QMessageBox::critical(this, "危险操作", "这将删除所有设置和数据，包括：\n• 所有配置文件\n• 课程表\n• 学生名单\n• 点名历史\n• 弹幕内容等\n\n此操作不可撤销！\n\n确认要删除所有设置并退出程序吗？", QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) {
		m_doNotSave = true;
		close();
		QDir configDirObj(configDir);
		if (configDirObj.exists()) configDirObj.removeRecursively();
		QApplication::quit();
		exit(0);
	}
}
void ClassroomComputerSettings::on_save_triggered()
{
	isSettingError = 0;
	Config &config = Config::instance();
	config.setBarrage(ui->barrage->isChecked());
	config.setScreensaver(ui->screensaver->isChecked());
	QString subjects = ui->hiddenSubjectsEdit->text().trimmed().replace(" ", "").replace(",,", ",").replace(QRegularExpression("^,+|,+$"), "");
	config.setHiddenSubjects(subjects);
	QStringList ganfanTimes = ui->mealTimeLineEdit->text().split(",", Qt::SkipEmptyParts);
	QStringList ganfanMinutes;
	for (const QString &timeStr : ganfanTimes) {
		int minutes = timeStringToMinutes(timeStr.trimmed());
		if (minutes != -1) ganfanMinutes << QString::number(minutes);
		else showErrorMessage("干饭时间格式错误: " + timeStr);
	}
	config.setGanfanTimes(ganfanMinutes);
	QStringList shutdownSchedule = ui->shutdownTimeLineEdit->text().split(",", Qt::SkipEmptyParts);
	QStringList shutdownMinutes;
	for (const QString &timeStr : shutdownSchedule) {
		int minutes = timeStringToMinutes(timeStr.trimmed());
		if (minutes != -1) shutdownMinutes << QString::number(minutes);
		else showErrorMessage("关机时间格式错误: " + timeStr);
	}
	config.setShutdownTimes(shutdownMinutes);
	config.setEnrollmentTimestamp(ui->enrollmentDateTimeEdit->dateTime().toSecsSinceEpoch());
	config.setGaokaoTimestamp(ui->GaoKaoDateTimeEdit->dateTime().toSecsSinceEpoch());
	config.saveConfig();
	ui->subjectListWidget_2->setDisabled(1);
	for (int row = 0; row < ui->longTermTimetableTable->rowCount(); row++) {
		QTableWidgetItem *startItem = ui->longTermTimetableTable->item(row, 0);
		QTableWidgetItem *endItem = ui->longTermTimetableTable->item(row, 1);
		if (!startItem || startItem->text().isEmpty()) {
			ui->longTermTimetableTable->setCurrentCell(row, 0);
			ui->longTermTimetableTable->scrollToItem(startItem);
			showErrorMessage(QString("第%1行：开始时间为空").arg(row + 1));
			return;
		}
		if (!endItem || endItem->text().isEmpty()) {
			ui->longTermTimetableTable->setCurrentCell(row, 1);
			ui->longTermTimetableTable->scrollToItem(endItem);
			showErrorMessage(QString("第%1行：结束时间为空").arg(row + 1));
			return;
		}
		QTime startTime = QTime::fromString(startItem->text(), "HH:mm");
		QTime endTime = QTime::fromString(endItem->text(), "HH:mm");
		if (!startTime.isValid()) {
			ui->longTermTimetableTable->setCurrentCell(row, 0);
			ui->longTermTimetableTable->scrollToItem(startItem);
			showErrorMessage(QString("第%1行：开始时间格式错误").arg(row + 1));
			return;
		}
		if (!endTime.isValid()) {
			ui->longTermTimetableTable->setCurrentCell(row, 1);
			ui->longTermTimetableTable->scrollToItem(endItem);
			showErrorMessage(QString("第%1行：结束时间格式错误").arg(row + 1));
			return;
		}
	}
	QFile file(timetableFilePath);
	if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
		showErrorMessage("长期课程表文件异常, 无法保存!");
		return;
	}
	QTextStream out(&file);
	out << "开始时间,结束时间,课程标题,周一,周二,周三,周四,周五,周六,周日\n";
	for (int row = 0; row < ui->longTermTimetableTable->rowCount(); row++) {
		QStringList rowData;
		for (int col = 0; col < ui->longTermTimetableTable->columnCount(); col++) {
			QTableWidgetItem *item = ui->longTermTimetableTable->item(row, col);
			QString text = item ? item->text() : "";
			text = text.trimmed();
			if (text.isEmpty()) { text = "-"; }
			rowData << text;
		}
		out << rowData.join(",") << "\n";
	}
	file.close();
	if (ui->tempScheduleTable->isEnabled()) {
		QFile file(tempTimetableFilePath);
		if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
			QTextStream out(&file);
			for (int row = 0; row < ui->TempTimetableTable->rowCount(); ++row) {
				QTableWidgetItem *item = ui->TempTimetableTable->item(row, 0);
				out << (item ? item->text() : "") << "\n";
			}
			file.close();
		}
	}
	QFile studentsfile(studentsFilePath);
	if (studentsfile.open(QIODevice::WriteOnly | QIODevice::Text)) {
		QTextStream(&studentsfile) << ui->studentListPlainTextEdit->toPlainText();
		studentsfile.close();
	}
	QFile noticefile(noticeFilePath);
	if (noticefile.open(QIODevice::WriteOnly | QIODevice::Text)) {
		QTextStream(&noticefile) << ui->noticePlainTextEdit->toPlainText();
		noticefile.close();
	}
	if (!isSettingError) {
		ui->statusLabel->setStyleSheet("");
		ui->statusLabel->setText("<p style='background-color: #00ff00'>已保存成功!</p>");
		repaint();
		update();
		QTimer::singleShot(3000, [=]() { ui->statusLabel->setText("教室多媒体设置"); });
	}
}
void ClassroomComputerSettings::on_doNotSave_triggered()
{
	m_doNotSave = true;
	close();
}
void ClassroomComputerSettings::on_openWebsite_triggered()
{
	QDesktopServices::openUrl(QUrl("https://gitee.com/linux-rm/classroom-computer/releases"));
	close();
}
void ClassroomComputerSettings::on_about_triggered() { QMessageBox::about(this, "关于", "教室多媒体系统\n\n版本信息:\nQt版本: " QT_VERSION_STR "\n编译时间: " __DATE__ " " __TIME__ "\n\n开发者:\n昵称: linux-rm\n邮箱: linux-rm@outlook.com\n计算机QQ群: 951234938\n项目地址: https://gitee.com/linux-rm/classroom-computer"); }
